const { getMaintenanceDetail, dealMaintenance, getMaintenanceByBattery } = require("../../utils/api");
const app = getApp()
import Dialog from '@vant/weapp/dialog/dialog';
Page({
  data: {
    userInfo: null, // 用户个人信息
    head: {
      myTitle: '长兴诺力运维',
      navBarHeight: 0,
      isBg: false,
    },
    backUnite: {
      manuallyInputVisible: false, // 控制悬浮输入框的显示/隐藏
    },
    faultReason: {
      activeFaultUnite: null, // 故障原因悬浮窗激活状态
    },
    battery: {
      maintenanceNumber: '',
      number: '',
      backUnite: [],
      faultReason: [],
      postType: '',
      faultDescription: {
        text: '',
        image: {},
      },
      facturer: '',
      model: '',
      detection: {
        description: '',
        image: [],
        report: '',
      },
    },
  },

  onLoad() {
    const h = app.globalData.navBarHeight * 2
    this.setData({
      userInfo: wx.getStorageSync('userInfo'),
      'head.navBarHeight': h,
    });
  },

  onPageScroll(e) {
    this.setData({
      'head.isBg': e.scrollTop < 40 ? false : true
    })
  },


  onReady() {
    console.log(app.globalData.navBarHeight)
    const h = app.globalData.navBarHeight * 2.2
    this.setData({
      'head.navBarHeight': h
    });
  },

  // 手输编号 输入框 显隐状态变更
  manuallyInputStatusChange() {
    this.setData({
      'backUnite.manuallyInputVisible': !this.data.backUnite.manuallyInputVisible,
    });
  },

  // 手动输入电池编号
  manuallyInputBatteryNumber(e) {
    this.setData({
      'battery.number': e.detail.value
    });
  },
  // 手输编号确认查询
  confirmManuallyInput() {
    const MaintenanceNumber = this.data.battery.maintenanceNumber;
    this.refreshPage();
    this.setData({
      'battery.maintenanceNumber': MaintenanceNumber
    })
    if (MaintenanceNumber) {
      const data = { PhoneNumber: this.data.userInfo.PhoneNumber, MaintenanceNumber: this.data.battery.maintenanceNumber }
      getMaintenanceDetail(data).then(res => {
        if (res.code === 4002050) {
          let image = [];
          if (res.data.DetectionResultFirstPhoto !== null) {
            image.push({url: res.data.DetectionResultFirstPhoto})
          }
          if (res.data.DetectionResultSecondPhoto !== null) {
            image.push({url: res.data.DetectionResultSecondPhoto})
          }
          if (res.data.DetectionResultThirdPhoto !== null) {
            image.push({url: res.data.DetectionResultThirdPhoto})
          }
          if (res.data.DetectionResultFourthPhoto !== null) {
            image.push({url: res.data.DetectionResultFourthPhoto})
          }
          const list = res.data.GetBatteryUnite || [];
          const backUnite = res.data.BackBatteryUnite.map(item =>{
            return {
              number: item,
              checked: list.includes(item)
            }
          })
          this.setData({
            'battery.backUnite': backUnite,
            'battery.faultReason': res.data.FaultReasonList,
            'battery.postType': res.data.FaultPostType,
            'battery.faultDescription.text': res.data.FaultPostReason,
            'battery.faultDescription.image.First': res.data.FaultPhotoFirst,
            'battery.faultDescription.image.Second': res.data.FaultPhotoSecond,
            'battery.faultDescription.image.Third': res.data.FaultPhotoThird,
            'battery.faultDescription.image.Fourth': res.data.FaultPhotoFourth,
            'battery.model': res.data.BatteryModel,
            'battery.facturer': res.data.BackManufacturer,
            'battery.detection.description': res.data.DetectionResult,
            'battery.detection.image': image,
            'battery.detection.report': res.data.MaintenanceReport,
          })
        } else {
          wx.showToast({
            title: '查询失败:' + res.msg,
            icon: 'none'
          })
        }
      });
    } else {
      wx.showToast({
        title: '请输入有效内容',
        icon: 'none'
      });
    }
  },
  // 扫码输入电池编号
  scanCodeInputBatteryNumber() {
    wx.scanCode({
      success: (res) => {
        console.log('扫描结果:', res.result);
        this.refreshPage();
        this.setData({ 
          'battery.number': res.result,
        });
        this.confirmScanCodeInput();
      },
      fail: (err) => {
        console.log('扫码失败:', err);
        wx.showToast({
          title: '扫码失败，请重试',
          icon: 'none',
        })
      }
    })
  },
  // 确认扫码输入电池编号
  confirmScanCodeInput() {
    const number = this.data.battery.number;
    this.refreshPage();
    this.setData({
      'battery.number': number
    })
    if (number) {
      const data = { PhoneNumber: this.data.userInfo.PhoneNumber, BatteryNumber: this.data.battery.number }
      getMaintenanceByBattery(data).then(res => {
        if (res.code === 4002060) {
          let image = [];
          if (res.data.DetectionResultFirstPhoto !== null) {
            image.push({url: res.data.DetectionResultFirstPhoto})
          }
          if (res.data.DetectionResultSecondPhoto !== null) {
            image.push({url: res.data.DetectionResultSecondPhoto})
          }
          if (res.data.DetectionResultThirdPhoto !== null) {
            image.push({url: res.data.DetectionResultThirdPhoto})
          }
          if (res.data.DetectionResultFourthPhoto !== null) {
            image.push({url: res.data.DetectionResultFourthPhoto})
          }
          const list = res.data.GetBatteryUnite || [];
          const backUnite = res.data.BackBatteryUnite.map(item =>{
            return {
              number: item,
              checked: list.includes(item)
            }
          })
          this.setData({
            'battery.maintenanceNumber': res.data.MaintenanceNumber,
            'battery.backUnite': backUnite,
            'battery.faultReason': res.data.FaultReasonList,
            'battery.postType': res.data.FaultPostType,
            'battery.faultDescription.text': res.data.FaultPostReason,
            'battery.faultDescription.image.First': res.data.FaultPhotoFirst,
            'battery.faultDescription.image.Second': res.data.FaultPhotoSecond,
            'battery.faultDescription.image.Third': res.data.FaultPhotoThird,
            'battery.faultDescription.image.Fourth': res.data.FaultPhotoFourth,
            'battery.model': res.data.BatteryModel,
            'battery.facturer': res.data.BackManufacturer,
            'battery.detection.description': res.data.DetectionResult,
            'battery.detection.image': image,
            'battery.detection.report': res.data.MaintenanceReport,
          })
        } else {
          wx.showToast({
            title: '查询失败:' + res.msg,
            icon: 'none'
          })
        }
      });
    } else {
      wx.showToast({
        title: '请输入有效内容',
        icon: 'none'
      });
    }
  },

  uniteCheckStatusChange(e) {
    const path = 'battery.backUnite[' + e.currentTarget.dataset.index + '].checked'
    this.setData({
      [path]: !this.data.battery.backUnite[e.currentTarget.dataset.index].checked
    })
  },

  // 打开故障原因下 电池子编号悬浮窗
  openFaultUniteCheck(e) {
    if (!this.data.battery.faultReason.MultipleSelections) {
      return
    }
    this.setData({
      'faultReason.activeFaultUnite': e.currentTarget.dataset.index
    });
  },

  // 关闭故障原因下 电池子编号悬浮窗
  closeFaultUniteCheck() {
    this.setData({
      'faultReason.activeFaultUnite': null
    })
  },

  // 检测结果更新
  faultDescriptionChange(e) {
    this.setData({
      'battery.detection.description': e.detail.value
    });
  },

  // 上传图片
  chooseImage(e) {
    let image = this.data.battery.detection.image;
    image.push({url: e.detail.file.url});
    this.setData({
      'battery.detection.image': image
    });
  },

  removeImage(e) {
    const index = e.detail.index;
    const image = this.data.battery.detection.image;
    image.splice(index, 1);
    this.setData({
      'battery.detection.image': image
    });
  },

  chooseReport() {
    wx.chooseMessageFile({
      count: 1, // 只允许选择一个文件
      type: 'file', // 支持所有文件类型
      success: (res) => {
        const file = res.tempFiles[0]; // 获取选中的文件信息
        const fileName = file.name; // 文件名
        // 更新数据
        this.setData({
          'battery.detection.report': file.path, // 文件的临时路径
        });
      },
      fail: (err) => {
        console.error('File selection failed:', err);
      }
    });
  },
  // 提交
  submit() {
    console.log('提交售后记录中...');
    const { battery } = this.data;

    // 提交前进行数据有效性验证
    
    // 构建要发送的数据对象
    let FaultReasonList = {};
    const BackBatteryUnite = battery.backUnite.filter(unit => unit.Checked || unit.Checked === 'allTrue').map(unit => unit.UniteNumber)
    battery.faultReason.forEach(faultReason => {
      if (faultReason.Checked) {
        if (faultReason.MultipleSelections) {
          FaultReasonList[faultReason.FaultName] = faultReason.BatteryUnite.filter(unit => unit.Checked).map(unit => unit.UniteNumber).map(element => BackBatteryUnite.indexOf(element) + 1)
        } else {
          FaultReasonList[faultReason.FaultName] = BackBatteryUnite.map(element => BackBatteryUnite.indexOf(element))
        }
      }
    });
    const confirmReceiveUnite = this.data.battery.backUnite
    .filter(item => item.checked)
    .map(item => item.number);
    if (confirmReceiveUnite.length === 0) {
      wx.showToast({
        title: '请选择已经收到的电池！',
        icon: 'none'
      })
      return
    }
    const formData = {
      PhoneNumber: parseInt(this.data.userInfo.PhoneNumber, 10),
      MaintenanceNumber: this.data.battery.maintenanceNumber,
      DetectionResult: this.data.battery.detection.description,
      GetBatteryUnite: JSON.stringify(confirmReceiveUnite)
    };
    dealMaintenance(formData).then(res => {
      if (res.code === 4002070) {
        const image = this.data.battery.detection.image.map((item, index) => {
          return {
            ...item,
            index: index
          }
        })
        const report = this.data.battery.detection.report
        if (image && image.length > 0) {
          const uploadPromises = image
          .filter(imageUrl => (imageUrl.url.startsWith('http://tmp/') || imageUrl.url.startsWith('wxfile://')))
          .map((imageUrl) => {
            let photoName; // 提前声明 photoName 变量
            if (imageUrl.index == 0) {
              photoName = 'DetectionResultFirstPhoto';
            } else if (imageUrl.index == 1) {
              photoName = 'DetectionResultSecondPhoto';
            } else if (imageUrl.index == 2) {
              photoName = 'DetectionResultThirdPhoto';
            } else {
              photoName = 'DetectionResultFourthPhoto';
            }
            console.log(imageUrl.url)
            return new Promise((resolve, reject) => {
              wx.uploadFile({
                url: 'https://cxnoblelift.com:8000/AfterSale/PostFaultImage/', // 确保这是正确的上传接口URL
                filePath: imageUrl.url, // 直接使用原始的本地文件路径
                name: 'MaintenancePhoto', // 固定的文件字段名
                formData: {
                  'MaintenanceNumber': this.data.battery.maintenanceNumber, // 确保 res.data 是你想要传递的 MaintenanceNumber
                  'PhotoName': photoName // 使用确定好的照片名称
                },
                success(res) {
                  console.log(1111)
                  console.log(`第${imageUrl.index + 1}张图片上传成功`, res.data);
                  resolve(res);
                },
                fail(err) {
                  console.error(`第${imageUrl.index + 1}张图片上传失败`, err);
                  wx.showToast({
                    title: '`第${imageUrl.index + 1}张图片上传失败,请重试！`',
                    icon: 'none'
                  })
                  reject(err);
                }
              });
            });
          });
          // 并行上传所有图片
          Promise.all(uploadPromises).then(() => {
            console.log('所有图片上传完成');
          }).catch(err => {
            console.error('部分图片上传失败:', err);
          });
        }
        if (report !== '' && typeof(report) === 'string') {
          wx.uploadFile({
            url: 'https://cxnoblelift.com:8000/AfterSale/PostFaultImage/',
            filePath: report,
            name: 'MaintenancePhoto',
            formData: {
              'MaintenanceNumber': this.data.battery.maintenanceNumber,
              'PhotoName': 'MaintenanceReport'
            },
            success(res) {
              console.log('检测报告上传成功！', res.data);
            },
            fail(err) {
              console.error('检测报告上传失败！', err);
              wx.showToast({
                title: '检测报告上传失败！请重试！',
                icon: 'none'
              })
              // reject(err);
            }
          });
        }
        Dialog.alert({
          message: '提交成功',
          theme: 'round-button',
        }).then(() => {
          
        })
        this.refreshPage()
      } else {
        console.error('提交失败:', res);
        wx.showToast({
          title: res.msg,
          icon: 'none'
        });
      }
    });
  },

  downLoadReport() {
    const fileSystemManager = wx.getFileSystemManager(); // 获取文件系统管理器

    wx.showLoading({
      title: '正在下载...',
    });
  
    // Step 1: 下载文件到临时路径
    wx.downloadFile({
      url: this.data.battery.detection.report, // 文件的远程 URL
      success: function (res) {
        if (res.statusCode === 200) {
          wx.openDocument({
            filePath: res.tempFilePath,
            fileType: 'docx', // 根据实际情况填写
            success: function (res) {
              console.log('打开文档成功');
            }
          });
        }
      },
      fail(err) {
        wx.showToast({
          title: '下载失败',
          icon: 'none',
        });
        console.error('文件下载失败:', err);
      },
      complete() {
        wx.hideLoading();
      },
    });
  },

  batteryDetectionDescriptionChange(e) {
    this.setData({
      'battery.detection.description': e.detail
    })
  },

  refreshPage() {
    this.setData({
      battery: {
        maintenanceNumber: '',
        number: '',
        backUnite: [],
        faultReason: [],
        postType: '',
        faultDescription: {
          text: '',
          image: {},
        },
        facturer: '',
        model: '',
        detection: {
          description: '',
          image: {},
          report: null,
        },
      },
    })
  }
});
 